import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
import useStore from '@/store'
import Confirm from '@/components/confirm'
const router = createRouter({
  history: createWebHashHistory(),
  // history: createWebHistory(),
  scrollBehavior: (to, from, savedPosition) => {
    // return {
    //始终滚动到顶部
    // top: 0,
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
    // }
  },
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: Home },
        { path: '/category/:id', component: () => import('@/views/category/index.vue') },
        { path: '/category/sub/:id', component: () => import('@/views/category/sub.vue') },
        { path: '/goods/:id', component: () => import('@/views/goods/index.vue'), },
        { path: '/cart', component: () => import('@/views/cart/index.vue') },
        { path: '/member/checkout', component: () => import('@/views/member/pay/checkout.vue') },
        { path: '/member/pay', component: () => import('@/views/member/pay/index.vue') },
        { path: '/pay/callback', component: () => import('@/views/member/pay/callback.vue') },
        {
          path: '/member', component: () => import('@/views/member/layout/index.vue'),
          children: [
            { path: '', component: () => import('@/views/member/home/index.vue') },
            // 不写斜杠会拼接
            { path: 'order', component: () => import('@/views/member/order/index.vue') }
          ]
        }
      ]
    },
    { path: '/login', component: () => import('@/views/login/index.vue') },
    { path: '/playground', component: () => import('@/views/playground/index.vue') },
    { path: '/login/callback', component: () => import('@/views/login/callback.vue') },

  ]
})

//路由前置守卫
// to 去哪 from 从哪来 next()放行函数  使用和router.push写什么 next()就写什么
router.beforeEach((to, from, next) => {
  const { user } = useStore()
  //判断是否登录 登陆了想去哪就去哪
  // 没有登录 只能访问部分页面
  const { cart } = useStore()
  if (cart.isLogin) {
    next()
  } else {
    if (to.path.indexOf('member') !== -1) {
      // if(to.path.includes('/member')){
      Confirm({ title: '温馨提示', text: '要登录了才能下单哦，现在去登录嘛？' }).then(() => {
        next({
          path: '/login',
          query: { redirectUrl: to.fullPath }
        })
        // user.query = to.fullPath
      }).catch(() => { })
    } else {
      next()
    }
  }
})
export default router